package com.rp.common.utils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

/**
 * 类说明: String字符串算术表达式进行Boolean判断
 *
 * @author ****
 * @date 2020-12-26 11:35  新建
 */

public class StringToBoolean {

    /**
     * @Author HuJingYu
     * @Date 11:38 2020-12-26
     * @Description String字符串算术表达式进行Boolean判断
     * @param string  String字符串算术表达式
     * @param map 带入判断的值
     * @return java.lang.Boolean
     */
    public static Boolean getBooelan(String string, Map<String, Object> map) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        for(String key : map.keySet()){
            engine.put(key, map.get(key));
        }
        Object result = engine.eval(string);
        return (Boolean) result;
    }

    public static void main(String[] args) throws ScriptException {
        //开始main方法
        String str = "value>8 || (value <= 5 && value > 1)";
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        engine.put("value", 10);
        Object result = engine.eval(str);
        System.out.println("计算结果:" + result);
    }
}
